package com.yami.shop.common.util;


import cn.hutool.core.util.StrUtil;

import com.aliyun.oss.common.utils.HttpUtil;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * IP帮助工具
 * @author yami
 */
public class IPHelper {
    private static final String UNKNOWN = "unknown";
    private static DbSearcher searcher;
    /**
     * 得到用户的真实地址,如果有多个就取第一个
     *
     * @return
     */
    public static String getIpAddr() {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (request == null) {
            return null;
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] ips = ip.split(",");
        return ips[0].trim();
    }
    public static String getIpProvinceAddr(String ip) {
        if(StrUtil.isBlank(ip)){
            return null;
        }
        String address = getAddress(ip);
        System.out.println("用户地址-》"+ip+"address"+address);
        String addresss = null;
        if(StrUtil.isNotBlank(address)){
            String[] split = address.split("\\|");
            addresss =  split.length>2? split[2]:null;//获取省份
        }
        if("0".equals(addresss)){//内网ip
            addresss = null;
        }
        if(StrUtil.isNotEmpty(addresss) && addresss.contains("省")){
            addresss = addresss.replace("省","");
        }
        return addresss;
    }
    public static void main(String[] args) {
        String address = getIpProvinceAddr("124.114.129.2");
        System.out.println(address);
    }
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据ip获取归属地
     * @param ip
     * @return
     */
    public static String getAddress(String ip) {
        //查询算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        //DbSearcher.BINARY_ALGORITHM //Binary
        //DbSearcher.MEMORY_ALGORITYM //Memory
        try {
            DbConfig config = null;
            File htmlFile = null;
            if(Objects.isNull(searcher)){
                System.out.println("配置失败，临时获取");
                //此处是为了获取Jar包部署所在文件夹
                //设置文件系统中的模板文件，，templateName是我方法传过来的，可以自定义
                InputStream resourceAsStream = HttpUtil.class.getClassLoader().getResourceAsStream("ipdb/ip2region.db");
                try {
                    htmlFile = File.createTempFile("temp", ".db");
                    inputStreamToFile(resourceAsStream,htmlFile);
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                config = new DbConfig();
                searcher = new DbSearcher(config,htmlFile.getPath());
            }
            Method method;
            switch (algorithm){
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
                default:
                    return null;
            }
            DataBlock dataBlock;
            dataBlock  = (DataBlock) method.invoke(searcher, ip);
            if (!Objects.isNull(htmlFile) && htmlFile.exists()) {
                htmlFile.delete();
            }
            return dataBlock.getRegion();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
